import {CloseCircleOutlined} from '@ant-design/icons';
import {
    FooterToolbar,
    PageContainer,
    ProForm,
    ProFormSelect,
    ProFormText,
    ProFormDigit, ProFormRadio, ProFormDateTimePicker, ProFormContext,
} from '@ant-design/pro-components';
import {Card, Col, message, Popover, Row, Form, InputNumber, Select, FormInstance} from 'antd';
import type {FC} from 'react';
import React, {useEffect, useRef, useState} from 'react';
import {organizationOrderAdd} from './service';
import useStyles from './style.style';
import {dataCenterSelectList} from "@/pages/power/data-center-list/service";
import {useRequest} from 'ahooks'; // 假设你在使用 ahooks 库
import {resourceSelectList} from "./service";
import {Link, useParams, useNavigate} from 'react-router-dom';
import {OrganizationListItem} from "@/pages/organization/org-list/data";
import {organizationDetail} from "@/pages/organization/org-list/service";
import {userSelectList} from "@/pages/organization/user-list/service";

type InternalNamePath = (string | number)[];
const fieldLabels = {
    organizationId: '租户ID',
    organizationName: '租户名称',
    dataCenterId: '资源池',
    skuId: '规格',
};

const {Option} = Select;

interface ErrorField {
    name: InternalNamePath;
    errors: string[];
}

const OrganizationOrderAddForm: FC<Record<string, any>> = () => {
    const navigate = useNavigate();
    const params: Record<string, any> = useParams();
    const {styles} = useStyles();
    const [error, setError] = useState<ErrorField[]>([]);
    const onFinish = async (values: Record<string, any>) => {
        setError([]);
        try {
            await organizationOrderAdd(values);
            message.success('提交成功');
            navigate('/order/organization-order/list');
        } catch {
            // console.log
        }
    };
    const [organizationInfo, setOrganizationInfo] = useState<OrganizationListItem>();
    const [loading, setLoading] = useState(true);
    const formRef = useRef<FormInstance>();

    const [selectDataCenterId, setSelectDataCenterId] = useState('');
    const [selectResourceType, setSelectResourceType] = useState('');
    const storageSizeSelectSuffix = (
        <Select defaultValue="GB">
            <Option value="TB">TB</Option>
            <Option value="PB">PB</Option>
        </Select>
    );
    const handleDataCenterChange = (value: string) => {
        setSelectDataCenterId(value)
    };
    const handleResourceTypeChange = (value: string) => {
        setSelectResourceType(value)
    };

    useEffect(() => {
        if (selectDataCenterId && selectResourceType) {
            fetchOptionsResource()
        }
    }, [selectDataCenterId, selectResourceType]);

    const {data: optionsResource, run: fetchOptionsResource} = useRequest(
        async () => {
            const res = await resourceSelectList({dataCenterId: selectDataCenterId, resourceType: selectResourceType});
            console.log("res" + JSON.stringify(res))
            return res.data.map((item: { resourceName: string; resourceId: string; }) => ({
                label: item.resourceName,
                value: item.resourceId,
            }));
        },
        {
            manual: true, // 设置为手动触发
        }
    );


    useEffect(() => {
        const fetchOrganizatinData = async () => {
            try {
                const response = await organizationDetail({organizationId: params?.id});
                setOrganizationInfo(response.data);
            } catch (error) {
                console.error('Error fetching form data:', error);
            } finally {
                setLoading(false);
            }
        };
        fetchOrganizatinData();
    }, [params?.id]);
    const onFinishFailed = (errorInfo: any) => {
        setError(errorInfo.errorFields);
    };
    return (
        <div>
            {loading ? (
                <div>Loading...</div>
            ) : (
                <ProForm
                    layout="vertical"
                    initialValues={{
                        billingCycle: 'hour',
                        organizationId: organizationInfo?.organizationId,
                        organizationName: organizationInfo?.name,
                    }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                >
                    <PageContainer>
                        <Card title="基本信息" className={styles.card} bordered={false}>
                            <Row>
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormText
                                        label={fieldLabels.organizationId}
                                        name="organizationId"
                                        readonly={true}
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 8,
                                    }}
                                    md={{
                                        span: 12,
                                    }}
                                    sm={24}
                                >
                                    <ProFormText
                                        label={fieldLabels.organizationName}
                                        name="organizationName"
                                        readonly={true}
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 8,
                                    }}
                                    md={{
                                        span: 12,
                                    }}
                                    sm={24}
                                >
                                    <ProFormSelect
                                        label="销售"
                                        width="md"
                                        name="salesperson"
                                        request={async () => {
                                            const res = await userSelectList({});
                                            return res.data.map((item) => ({
                                                label: item.username,
                                                value: item.userid,
                                            }));
                                        }}
                                        // rules={[
                                        //     {
                                        //         required: true,
                                        //         message: '请选择销售人员',
                                        //     },
                                        // ]}
                                    />
                                </Col>
                            </Row>
                        </Card>
                        <Card title="资源信息" className={styles.card} bordered={false}>
                            <Row>
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormSelect
                                        label={fieldLabels.dataCenterId}
                                        name="dataCenterId"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请选择资源池',
                                            },
                                        ]}
                                        placeholder="请选择资源池"
                                        onChange={handleDataCenterChange}
                                        request={async () => {
                                            const res = await dataCenterSelectList({});
                                            return res.data.map((item: { name: any; dataCenterId: any; }) => ({
                                                label: item.name,
                                                value: item.dataCenterId,
                                            }));
                                        }}
                                    />
                                </Col>
                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 8,
                                    }}
                                    md={{
                                        span: 12,
                                    }}
                                    sm={24}
                                >
                                    <ProFormSelect
                                        label="资源类型"
                                        width="md"
                                        name="resourceType"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请选择资源类型',
                                            },
                                        ]}
                                        onChange={handleResourceTypeChange}
                                        valueEnum={{
                                            'host_computer': '主机',
                                            'storage': '存储',
                                            'network': '网络',
                                        }}
                                    />
                                </Col>
                                <Col
                                    xl={{span: 6, offset: 2,}}
                                    lg={{span: 8,}}
                                    md={{span: 12,}}
                                    sm={24}
                                >
                                    <ProFormSelect
                                        label="资源实例"
                                        width="md"
                                        name="resourceId"
                                        key={`${selectDataCenterId}-${selectResourceType}`}
                                        rules={[
                                            {
                                                required: true,
                                                message: '资源实例',
                                            },
                                        ]}
                                        options={optionsResource}
                                    />
                                </Col>
                            </Row>
                            <Row
                                hidden={selectResourceType != 'storage'}
                            >
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormDigit
                                        label="存储大小"
                                        name="resourceDesc"
                                        rules={[
                                            {
                                                required: selectResourceType == 'storage',
                                                message: '请输入存储大小',
                                            },
                                        ]}
                                        width={200}
                                        fieldProps={
                                            {addonAfter: storageSizeSelectSuffix}
                                        }
                                        placeholder="请输入存储大小"
                                    />
                                </Col>
                            </Row>
                        </Card>
                        <Card title="账单信息" className={styles.card} bordered={false}>
                            <Row gutter={16}>
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormRadio.Group
                                        name="billingCycle"
                                        label="计费周期"
                                        options={[
                                            {
                                                label: '每小时',
                                                value: 'hour',
                                            },
                                            {
                                                label: '每天',
                                                value: 'day',
                                            },
                                            {
                                                label: '每月',
                                                value: 'month',
                                            },
                                        ]}
                                    />
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormDigit
                                        label="单价"
                                        name="unitPriceNumber"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入单价',
                                            },
                                        ]}
                                        width={200}
                                        fieldProps={{addonAfter: "元"}}
                                        placeholder="请输入单价"
                                    />
                                </Col>

                                <Col
                                    xl={{
                                        span: 6,
                                        offset: 2,
                                    }}
                                    lg={{
                                        span: 8,
                                    }}
                                    md={{
                                        span: 12,
                                    }}
                                    sm={24}
                                >
                                    <ProFormDateTimePicker
                                        label="开始计费时间（可选）"
                                        width="md"
                                        name="start"
                                        placeholder={'开始日期'}
                                        // disabled={true}
                                    />
                                </Col>
                            </Row>
                        </Card>
                    </PageContainer>
                </ProForm>
            )}
        </div>
    );
};
export default OrganizationOrderAddForm;
